package com.example.testhotload;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.widget.Toast;

public class ApkInstallReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
            long downloadApkId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1L);
            installApk(context,downloadApkId);
        }
    }

    private void installApk(Context context,long downloadApkId){
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        long downId = sp.getLong(DownloadManager.EXTRA_DOWNLOAD_ID,-1L);
        if(downloadApkId==downId){
            DownloadManager downloadManager =(DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
            Uri downloadFileUri = downloadManager.getUriForDownloadedFile(downloadApkId);
            if(downloadFileUri!=null){
                try{
                    Intent install = new Intent(Intent.ACTION_VIEW);
                    install.setDataAndType(downloadFileUri,"application/vnd.android,package-archive");
                    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    context.startActivity(install);
                }catch (Exception e){
                    e.printStackTrace();
                    return ;
                }

            }else{
                Toast.makeText(context,"下载失败",Toast.LENGTH_SHORT).show();
            }
        }
    }
}
